<?php
/**
 * @author GhostWei
 * @date 2012-5-31
 */
class picture_special_localeConcept extends system_concept_abstract {

	protected $_lang = null;
	public function __construct($lang = null) {
		$this->_lang = $lang;
		parent::__construct(array(), array());
	}
	
	public function init() {
		$this->setRowClass('picture_special_row');
		$this->setModel('picture_special_model', 'special');
		$this->setModelCols('special', array('id', 'name', 'cover', 'ptotal'));
		$this->setModelCols('special', array('display_order', 'is_recommend', 'is_active', 'creationtime', 'lastmodified'));
	}

	public function save(picture_special_row $row) {
		if(!preg_match('#[^\\\/\?\|\#]{2,50}#is', $row->getName())) {
			throw new picture_exception("Key Name formation error.");
		}
		
		$row->set('display_order', intval($row->getDisplayOrder()));
		$row->setIsActive(($row->get('is_active') ? 1 : 0));
		$row->setIsRecommend(($row->get('is_recommend') ? 1 : 0));
		if(!$row->getPtotal()) {
			$row->setPtotal(0);
		}
		/**
		 * 因为special ID 有变化，所以这里要先取到locale的完事row
		 * 不可以修改顺序
		 */
		$locale = $row->getLocale();
		if(!$locale->getTitle()) {
			throw new picture_exception("Title can not be empty.");
		}
		if($row->getId()) {
			if($this->getModel('special')->fetchRow(array('id != ?' => $row->getId(), 'name = ?' => $row->getName()))) {
				throw new picture_exception("This Special is already Existing.");
			}
	 		$row->setLastmodified(system_date::timestamp());
			$this->getModel('special')->update($row->getModelData('special'), array('id = ?' => $row->getId()));
		} else {
			if(!($eRow = $this->getModel('special')->fetchRow(array('name = ?' => $row->getName())))) {
				$row->setLastmodified(system_date::timestamp());
				$row->setCreationtime(system_date::timestamp());
				$id = $this->getModel('special')->insert($row->getModelData('special'));
				$row->setId($id);
			} else {
				$row->setId($eRow['id']);
			}
		}
		/**
		 * 用前面取到的 locale row
		 */
		$locale->setSpecialId($row->getId());
		$locale->save();
		/**
		 * 保存关键字
		 */
		$kConcept = new resource_keyword_concept();
		$pkConcept = new picture_special_keyword_concept();
		$pkModel = new picture_special_keyword_model();
		$pkModel->delete(array('special_id = ?' => $row->getId()));
		foreach($row->getKeywords() AS $keyword) {
			if(!$keyword) continue;
			if(!($kRow = $kConcept->fetch(array('name = ?' => $keyword)))) {
				$kRow = $kConcept->create();
				$kRow->setIsActive(1);
				$kRow->setName($keyword);
				$kRow = $kRow->save();
			}
			$pkRow = $pkConcept->create();
			$pkRow->setSpecialId($row->getId());
			$pkRow->setKeywordId($kRow->getId());
			$pkRow->save();
		}
		/**
		 * 保存分类
		 */
		$categoryModel = new picture_special_category_model();
		$categoryModel->delete("`special_id` = '{$row->getId()}' AND `lang` = '{$this->_lang}'");
		foreach($row->getCategoryList() AS $category_id) {
			$categoryModel->insert(array('lang' => $this->_lang, 'special_id' => $row->getId(), 'category_id' => $category_id));
		}
		$this->updateCategorySTotal($row->getCategoryList());
		$row->updatePhotoCount();
		return $row;
	}

	public function delete(picture_special_row $row, $options = array()) {
		$id = $row->getId();
		$db = system_db::getAdapter();
		$where = "`special_id` = '$id'";
		if(isset($options['locale_only'])) {
			$where .= " AND `lang` = '{$this->_lang}'";
		}
		$upCid = array();
		foreach($db->fetchAll("SELECT `category_id` FROM `picture_special_category` WHERE $where") AS $c) {
			$upCid[$c['category_id']] = $c['category_id'];
		}
		$db->query("DELETE FROM `picture_special_locale` WHERE $where");
		$db->query("DELETE FROM `picture_special_category` WHERE $where");
		if(!isset($options['reserve_collection'])) {
			$db->query("DELETE FROM `collection_photo` WHERE `special_id` IN(SELECT `id` FROM `collection_special` WHERE `link` IN(SELECT `link_key` FROM `picture_special_collection` WHERE `special_id` = '$id'))");
			$db->query("DELETE FROM `collection_special` WHERE `link` IN(SELECT `link_key` FROM `picture_special_collection` WHERE `special_id` = '$id')");
			$db->query("DELETE FROM `picture_special_collection` WHERE `special_id` = '$id'");
		}
		if(isset($options['delete_photo'])) {
			$concept = new picture_photo_localeConcept();
			$dpsSql = "(SELECT * FROM `picture_special_photo` WHERE `photo_id` IN(SELECT `photo_id` FROM `picture_special_photo` WHERE `special_id` = '$id')) AS C";
			$dpsSql = "SELECT `photo_id` FROM (SELECT COUNT(1) AS `d`,`photo_id` FROM $dpsSql GROUP BY photo_id) AS E WHERE `d` = 1";
			foreach($concept->fetchAll("id IN($dpsSql)") AS $photo) {
				$photo->delete($options);
			}
		}
		$db->query("DELETE FROM `picture_special_photo` WHERE `special_id` = '$id'");
		$db->query("DELETE FROM `picture_special_keyword` WHERE `special_id` = '$id'");
		if(!isset($options['locale_only'])) {
			$db->query("DELETE FROM `picture_special` WHERE `id` = '$id'");
			$db->query("DELETE FROM `picture_special_collection` WHERE `special_id` = '$id'");
		}
		$this->updateCategorySTotal($upCid);
	}
	
	public function updateCategorySTotal(array $cids) {
		foreach($cids AS $category_id) {
			system_db::getAdapter()->query("UPDATE `picture_category_locale` SET `stotal` = (
					SELECT COUNT(1) FROM `picture_special_category` WHERE `category_id` = '$category_id' AND `lang` = '{$this->_lang}'
				) WHERE `lang` = '{$this->_lang}' AND `category_id` = '$category_id'");
		}
	}

	protected $_locale = null;
	public function getLocale($row, $lang = null) {
		if($lang !== null) $this->_lang = $lang;
		if($this->_locale === null || $this->_locale->getSpecialId() != $row->getId()) {
			$concept = new picture_special_locale_concept();
			if(!($this->_locale = $concept->fetch(array('special_id = ?' => intval($row->getId()), 'lang = ?' => $this->_lang)))) {
				$this->_locale = $concept->create();
				$this->_locale->setLang($this->_lang);
				$this->_locale->setSpecialId(intval($row->getId()));
			}
		}
		return $this->_locale;
	}	
	
}
